package cdu.sl.aichatdemo.service.impl;

import cdu.sl.aichatdemo.mapper.CustomChatMemoryMapper;
import cdu.sl.aichatdemo.pojo.dto.ChatHistoryDto;
import cdu.sl.aichatdemo.pojo.entity.CustomChatMemory;
import cdu.sl.aichatdemo.service.ChatClientService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 聊天客户端服务实现类
 * @Author sunlin5@asiainfo.com
 * @Date 2025/8/28
 * @Version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatClientServiceImpl implements ChatClientService {

    private final CustomChatMemoryMapper customChatMemoryMapper;

    @Override
    public List<CustomChatMemory> getChatRecordsByConversationId(String conversationId) {
        log.info("查询对话记录，conversationId: {}", conversationId);
        List<CustomChatMemory> records = customChatMemoryMapper.selectByConversationId(conversationId);
        log.info("查询到对话记录数量: {}", records.size());
        return records;
    }

    @Override
    public List<CustomChatMemory> getChatHistoryByUserId(Long userId) {
        log.info("查询用户历史对话，userId: {}", userId);
        List<CustomChatMemory> history = customChatMemoryMapper.selectHistoryByUserId(userId);
        log.info("查询到历史对话数量: {}", history.size());
        return history;
    }

    @Override
    public List<CustomChatMemory> getChatDetailsByUserIdAndConversationId(Long userId, String conversationId) {
        log.info("查询具体对话内容，userId: {}, conversationId: {}", userId, conversationId);
        List<CustomChatMemory> details = customChatMemoryMapper.selectByUserIdAndConversationId(userId, conversationId);
        log.info("查询到对话详情数量: {}", details.size());
        return details;
    }

    @Override
    public List<ChatHistoryDto> getChatHistoryDtoByUserId(Long userId) {
        log.info("查询用户历史对话DTO，userId: {}", userId);
        List<CustomChatMemory> historyRecords = customChatMemoryMapper.selectHistoryByUserId(userId);
        
        List<ChatHistoryDto> historyDtos = new ArrayList<>();
        for (CustomChatMemory record : historyRecords) {
            ChatHistoryDto dto = new ChatHistoryDto();
            dto.setConversationId(record.getConversationId());
            dto.setUserId(record.getUserId());
            dto.setTitle(record.getTitle());
            dto.setCreatedAt(record.getCreatedAt());
            
            // 查询该对话的消息数量
            QueryWrapper<CustomChatMemory> countWrapper = new QueryWrapper<>();
            countWrapper.eq("conversation_id", record.getConversationId())
                       .eq("status", "active");
            Long messageCount = customChatMemoryMapper.selectCount(countWrapper);
            dto.setMessageCount(messageCount.intValue());
            
            // 获取最后一条消息内容作为预览
            QueryWrapper<CustomChatMemory> lastMessageWrapper = new QueryWrapper<>();
            lastMessageWrapper.eq("conversation_id", record.getConversationId())
                             .eq("status", "active")
                             .orderByDesc("order_index")
                             .last("LIMIT 1");
            CustomChatMemory lastMessage = customChatMemoryMapper.selectOne(lastMessageWrapper);
            if (lastMessage != null) {
                String preview = lastMessage.getContent().length() > 50 
                    ? lastMessage.getContent().substring(0, 50) + "..." 
                    : lastMessage.getContent();
                dto.setLastMessage(preview);
            }
            
            historyDtos.add(dto);
        }
        
        log.info("转换后的历史对话DTO数量: {}", historyDtos.size());
        return historyDtos;
    }
}
